<template>
  <el-dialog 
    v-model="visible" 
    title="选择商品规格" 
    :width="isMobile ? '95vw' : '600px'"
    :before-close="handleClose"
    :class="{ 'mobile-dialog': isMobile }"
  >
    <div class="product-info" v-if="product">
      <!-- 商品基本信息 -->
      <div class="product-summary" :class="{ 'mobile': isMobile }">
        <img :src="product.mainImage" :alt="product.name" class="product-image" />
        <div class="product-details">
          <h3 class="product-name">{{ product.name }}</h3>
          <div class="price-info">
            <span class="current-price"
              >￥{{ selectedStock?.discountPrice || selectedStock?.price || product.price }}</span
            >
            <span
              v-if="
                selectedStock?.discountPrice && selectedStock.price > selectedStock.discountPrice
              "
              class="original-price"
            >
              ￥{{ selectedStock.price }}
            </span>
          </div>
          <div class="stock-info" v-if="selectedStock">
            库存：{{ selectedStock.stockQuantity }}件
          </div>
        </div>
      </div>

      <!-- 规格选择 -->
      <div class="spec-selection">
        <!-- 颜色选择 -->
        <div class="spec-group" v-if="availableColors.length > 0">
          <label class="spec-label">颜色：</label>
          <div class="spec-options" :class="{ 'mobile': isMobile }">
            <el-button
              v-for="color in availableColors"
              :key="color.colorId"
              :type="selectedColor?.colorId === color.colorId ? 'primary' : 'default'"
              :size="isMobile ? 'large' : 'small'"
              @click="selectColor(color)"
              class="spec-button"
            >
              {{ color.colorName }}
            </el-button>
          </div>
        </div>

        <!-- 尺寸选择 -->
        <div class="spec-group" v-if="availableSizes.length > 0">
          <label class="spec-label">尺寸：</label>
          <div class="spec-options" :class="{ 'mobile': isMobile }">
            <el-button
              v-for="size in availableSizes"
              :key="size.sizeId"
              :type="selectedSize?.sizeId === size.sizeId ? 'primary' : 'default'"
              :disabled="!isSizeAvailable(size)"
              :size="isMobile ? 'large' : 'small'"
              @click="selectSize(size)"
              class="spec-button"
            >
              {{ size.shoeSize }}
            </el-button>
          </div>
        </div>

        <!-- 数量选择 -->
        <div class="quantity-group" :class="{ 'mobile': isMobile }">
          <label class="spec-label">数量：</label>
          <el-input-number
            v-model="quantity"
            :min="1"
            :max="selectedStock?.stockQuantity || 999"
            :disabled="!selectedStock || selectedStock.stockQuantity === 0"
            :size="isMobile ? 'large' : 'default'"
            :controls="isMobile"
            class="quantity-input"
          />
        </div>
      </div>

      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-message">
        <el-alert :title="errorMessage" type="error" show-icon :closable="false" />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer" :class="{ 'mobile': isMobile }">
        <el-button 
          @click="handleClose"
          :size="isMobile ? 'large' : 'default'"
          class="cancel-btn"
        >
          取消
        </el-button>
        <el-button
          type="primary"
          :disabled="!canAddToCart"
          :loading="loading"
          :size="isMobile ? 'large' : 'default'"
          @click="handleAddToCart"
          class="action-btn"
        >
          {{ props.buyNowMode ? '立即购买' : '加入购物车' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, withDefaults } from 'vue'
import { ElMessage } from 'element-plus'
import { productService } from '@/api'
import { useCartStore } from '@/stores/cart'
import { useResponsive } from '@/utils/responsive'
import type { ProductDetail } from '@/types/product'

interface Stock {
  skuId: number
  shoeId: number
  sizeId: number
  colorId: number
  price: number
  discountPrice?: number
  stockQuantity: number
  shoe?: {
    shoeId: number
    name: string
    productImageUrl: string
  }
  size?: {
    sizeId: number
    shoeSize: string
  }
  color?: {
    colorId: number
    colorName: string
  }
}

interface Color {
  colorId: number
  colorName: string
}

interface Size {
  sizeId: number
  shoeSize: string
}

interface Props {
  visible: boolean
  product: ProductDetail | null
  buyNowMode?: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success', skuId?: number): void
}

const props = withDefaults(defineProps<Props>(), {
  buyNowMode: false,
})
const emit = defineEmits<Emits>()
const cartStore = useCartStore()
const { isMobile } = useResponsive()

// 响应式数据
const loading = ref(false)
const quantity = ref(1)
const stockList = ref<Stock[]>([])
const selectedColor = ref<Color | null>(null)
const selectedSize = ref<Size | null>(null)
const errorMessage = ref('')

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
})

// 获取所有可用的颜色
const availableColors = computed(() => {
  const colors = new Map<number, Color>()
  stockList.value.forEach((stock) => {
    if (stock.color && stock.stockQuantity > 0) {
      colors.set(stock.colorId, {
        colorId: stock.colorId,
        colorName: stock.color.colorName,
      })
    }
  })
  return Array.from(colors.values())
})

// 获取当前颜色下可用的尺寸
const availableSizes = computed(() => {
  if (!selectedColor.value) return []

  const sizes = new Map<number, Size>()
  stockList.value
    .filter((stock) => stock.colorId === selectedColor.value?.colorId && stock.stockQuantity > 0)
    .forEach((stock) => {
      if (stock.size) {
        sizes.set(stock.sizeId, {
          sizeId: stock.sizeId,
          shoeSize: stock.size.shoeSize,
        })
      }
    })
  return Array.from(sizes.values())
})

// 获取当前选中的库存信息
const selectedStock = computed(() => {
  if (!selectedColor.value || !selectedSize.value) return null

  return (
    stockList.value.find(
      (stock) =>
        stock.colorId === selectedColor.value?.colorId &&
        stock.sizeId === selectedSize.value?.sizeId,
    ) || null
  )
})

// 检查是否可以加入购物车
const canAddToCart = computed(() => {
  return (
    selectedColor.value &&
    selectedSize.value &&
    selectedStock.value &&
    selectedStock.value.stockQuantity > 0 &&
    quantity.value > 0 &&
    quantity.value <= selectedStock.value.stockQuantity
  )
})

// 方法
const loadProductStock = async () => {
  if (!props.product) return

  loading.value = true
  errorMessage.value = ''

  try {
    const response = await productService.getStockListByProduct(props.product.productId)
    stockList.value = (response.data.data as Stock[]) || []

    // 如果没有库存数据，显示错误信息
    if (stockList.value.length === 0) {
      errorMessage.value = '该商品暂无库存信息'
    }
  } catch (error) {
    console.error('加载商品库存失败:', error)
    errorMessage.value = '加载商品库存失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const selectColor = (color: Color) => {
  selectedColor.value = color
  // 重置尺寸选择
  selectedSize.value = null
  errorMessage.value = ''
}

const selectSize = (size: Size) => {
  selectedSize.value = size
  errorMessage.value = ''
}

const isSizeAvailable = (size: Size) => {
  if (!selectedColor.value) return false

  const stock = stockList.value.find(
    (s) => s.colorId === selectedColor.value?.colorId && s.sizeId === size.sizeId,
  )
  return stock && stock.stockQuantity > 0
}

const handleAddToCart = async () => {
  if (!canAddToCart.value || !selectedStock.value) {
    errorMessage.value = '请选择完整的商品规格'
    return
  }

  loading.value = true

  try {
    const result = await cartStore.addToCart(selectedStock.value.skuId, quantity.value)

    if (result.success) {
      ElMessage.success(props.buyNowMode ? '已添加到购物车，即将跳转' : '已添加到购物车')
      // 【重要】立刻购买模式下传递SKU ID，用于购物车页面默认选中该商品
      // 此功能确保用户点击立刻购买后，跳转到购物车时该商品被自动选中
      // ⚠️ 请勿删除此逻辑，否则会影响用户购买体验
      emit('success', props.buyNowMode ? selectedStock.value.skuId : undefined)
      handleClose()
    } else {
      errorMessage.value = result.error || '添加失败'
    }
  } catch (error) {
    console.error('添加到购物车失败:', error)
    errorMessage.value = '添加失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  visible.value = false
  // 重置状态
  selectedColor.value = null
  selectedSize.value = null
  quantity.value = 1
  errorMessage.value = ''
}

// 监听弹窗显示状态
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible && props.product) {
      loadProductStock()
    }
  },
)
</script>

<style scoped lang="scss">
// 移动端对话框样式
:deep(.mobile-dialog) {
  .el-dialog {
    margin: 10px auto !important;
    border-radius: 16px;
    
    .el-dialog__header {
      padding: 20px 20px 16px;
      
      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
      }
    }
    
    .el-dialog__body {
      padding: 0 20px 20px;
    }
    
    .el-dialog__footer {
      padding: 0 20px 20px;
    }
  }
}

.product-info {
  .product-summary {
    display: flex;
    gap: 16px;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #ebeef5;

    &.mobile {
      flex-direction: column;
      gap: 12px;
      text-align: center;
      
      .product-image {
        width: 120px;
        height: 120px;
        margin: 0 auto;
      }
      
      .product-details {
        .product-name {
          font-size: 18px;
          margin-bottom: 12px;
        }
        
        .price-info {
          margin-bottom: 12px;
          
          .current-price {
            font-size: 20px;
          }
        }
      }
    }

    .product-image {
      width: 80px;
      height: 80px;
      object-fit: cover;
      border-radius: 8px;
      border: 1px solid #ebeef5;
    }

    .product-details {
      flex: 1;

      .product-name {
        margin: 0 0 8px 0;
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }

      .price-info {
        margin-bottom: 8px;

        .current-price {
          font-size: 18px;
          font-weight: 600;
          color: #e6a23c;
          margin-right: 8px;
        }

        .original-price {
          font-size: 14px;
          color: #909399;
          text-decoration: line-through;
        }
      }

      .stock-info {
        font-size: 14px;
        color: #606266;
      }
    }
  }

  .spec-selection {
    .spec-group {
      margin-bottom: 20px;

      .spec-label {
        display: inline-block;
        width: 60px;
        font-size: 14px;
        color: #606266;
        margin-bottom: 8px;
        font-weight: 500;
      }

      .spec-options {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;

        &.mobile {
          gap: 10px;
          
          .spec-button {
            min-width: 80px;
            height: 44px;
            font-size: 14px;
            border-radius: 8px;
            
            &:hover {
              transform: translateY(-1px);
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            }
          }
        }

        .el-button {
          margin: 0;
        }
        
        .spec-button {
          transition: all 0.2s ease;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          }
        }
      }
    }

    .quantity-group {
      display: flex;
      align-items: center;
      gap: 12px;

      &.mobile {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
        
        .spec-label {
          margin-bottom: 4px;
        }
        
        .quantity-input {
          width: 100%;
          
          :deep(.el-input-number__decrease),
          :deep(.el-input-number__increase) {
            width: 44px;
            height: 44px;
            font-size: 18px;
          }
          
          :deep(.el-input__inner) {
            height: 44px;
            font-size: 16px;
            text-align: center;
          }
        }
      }

      .spec-label {
        margin-bottom: 0;
      }
      
      .quantity-input {
        :deep(.el-input-number__decrease),
        :deep(.el-input-number__increase) {
          transition: all 0.2s ease;
          
          &:hover {
            background-color: #f5f7fa;
            color: #409eff;
          }
        }
      }
    }
  }

  .error-message {
    margin-top: 16px;
    
    :deep(.el-alert) {
      border-radius: 8px;
      
      .el-alert__title {
        font-size: 14px;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;

  &.mobile {
    flex-direction: column;
    gap: 10px;
    
    .el-button {
      width: 100%;
      height: 48px;
      font-size: 16px;
      border-radius: 8px;
      font-weight: 500;
    }
  }

  .cancel-btn {
    background-color: #f5f7fa;
    border-color: #dcdfe6;
    color: #606266;
    font-weight: 500;

    &:hover {
      background-color: #ebeef5;
      border-color: #dcdfe6;
      color: #409eff;
    }
  }

  .action-btn {
    background-color: #409eff;
    border-color: #409eff;
    color: #fff;
    font-weight: 500;

    &:hover {
      background-color: #66b1ff;
      border-color: #66b1ff;
      color: #fff;
    }
  }
}

// 移动端触摸优化
@media (max-width: 768px) {
  :deep(.el-dialog) {
    .el-dialog__header {
      .el-dialog__headerbtn {
        top: 20px;
        right: 20px;
        
        .el-dialog__close {
          font-size: 20px;
          width: 32px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          transition: all 0.2s ease;
          
          &:hover {
            background-color: #f5f7fa;
            color: #409eff;
          }
        }
      }
    }
  }
  
  .spec-button {
    touch-action: manipulation;
    -webkit-tap-highlight-color: transparent;
    
    &:active {
      transform: scale(0.98);
    }
  }
  
  .quantity-input {
    :deep(.el-input-number__decrease),
    :deep(.el-input-number__increase) {
      touch-action: manipulation;
      -webkit-tap-highlight-color: transparent;
      
      &:active {
        transform: scale(0.95);
      }
    }
  }
}

// 平板端优化
@media (min-width: 769px) and (max-width: 1024px) {
  :deep(.el-dialog) {
    .el-dialog__body {
      padding: 0 24px 24px;
    }
    
    .el-dialog__footer {
      padding: 0 24px 24px;
    }
  }
  
  .product-info {
    .product-summary {
      .product-image {
        width: 100px;
        height: 100px;
      }
      
      .product-details {
        .product-name {
          font-size: 17px;
        }
        
        .current-price {
          font-size: 19px;
        }
      }
    }
    
    .spec-selection {
      .spec-options {
        gap: 10px;
        
        .spec-button {
          min-width: 70px;
          height: 36px;
        }
      }
    }
  }
}
</style>
